package com.woyou.model;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.EBean.Scope;

import android.text.TextUtils;
import android.util.Log;

import com.woyou.bean.ChosenGoods;
import com.woyou.bean.Coupon;
import com.woyou.bean.Gift;
import com.woyou.bean.Goods;
import com.woyou.bean.IChoose;
import com.woyou.bean.Option;
import com.woyou.bean.OrderCouponItem;
import com.woyou.bean.OrderGoodsItem;
import com.woyou.bean.OrderOptionItem;
import com.woyou.bean.OrderSubGoodsItem;
import com.woyou.bean.ShopDetail;
import com.woyou.bean.ShoppingCar;
import com.woyou.bean.SubGoods;
import com.woyou.utils.ParseUtils;
import com.woyou.utils.eventbus.EventShoppingCarChange;

import de.greenrobot.event.EventBus;

@EBean(scope = Scope.Singleton)
public class ShoppingCarModel extends SuperModel {

	private static final String TAG = "ShoppingCarController";
	
	@Bean ActivitiesModel mActivitiesModel;
	
	@Bean GoodsModel mGoodsController;
	
	/**
	 * 购物车
	 */
	private ShoppingCar shoppingCar = new ShoppingCar();

	@AfterInject
	@Override
	protected void onInit() {
		
	}

	public float getdFee() {
		return shoppingCar.getdFee();
	}


	public int getTotal() {
		return shoppingCar.getTotal();
	}

	public void setTotal(int total) {
		shoppingCar.setTotal(total);
	}

	public float getTotalCost() {
		return shoppingCar.getTotalCost();
	}

	
	/**
	 * 选购的商品和餐盒费是否达到起送价格,不计算餐盒费和外送费
	 * 
	 * @return
	 */
	public boolean achieveSend() {
		BigDecimal b1 = new BigDecimal(shoppingCar.getToSendPrice());  
		double f1= b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();  
		
		BigDecimal b2 = new BigDecimal(shoppingCar.getBaseCost());  
		double f2= b2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();  
		
		if (f1 <= f2) {
			return true;
		}
		return false;
	}

	public void setTotalCost(float totalCost) {
		shoppingCar.setTotalCost(totalCost);
	}

	public List<IChoose> getGoodsList() {
		return shoppingCar.getGoodsList();
	}

	public List<Coupon> getCouponList() {
		return shoppingCar.getCouponList();
	}

	public void setCouponList(List<Coupon> couponList) {
		shoppingCar.setCouponList(couponList);
		calculate();
	}
	
	/**
	 * 清空优惠卷列表
	 */
	public void clearCouponList(){
		shoppingCar.getCouponList().clear();
		calculate();
	}
	
	/**
	 * 计算总份数和总价
	 */
	public void calculate() {
		shoppingCar.setBaseCost(0);
		shoppingCar.setTotal(0);
		shoppingCar.setTotalCost(0);
		for (IChoose choose : shoppingCar.getGoodsList()) {
			int chosenNum = choose.getChosenNum();
			// 设置购物车列表的已选数量
			shoppingCar.setTotal(shoppingCar.getTotal() + chosenNum);
			// if( cg.hasOption() ){
			// for( ChosenGoods cg : cg.getChoseGoodsList() ){
			float price = choose.getPrice();
			int num = choose.getChosenNum();
			shoppingCar.setBaseCost(shoppingCar.getBaseCost() + price * num);
			shoppingCar.setTotalCost(shoppingCar.getBaseCost());// 计算总价
			// }
			// }else{
			// shoppingCar.setBaseCost(shoppingCar.getBaseCost() +
			// (cg.getPrice()*cg.getChosenNum()));
			// shoppingCar.setTotalCost(shoppingCar.getBaseCost());
			// }
		}

		List<IChoose> list = getChosenGoodsList();
		if (list.size() > 0) {
			// 添加餐盒费和外送费
			if (shoppingCar.getMealsBoxFeeType() == 2) {
//				for (int i = 0; i < list.size(); i++) {
//					shoppingCar.setBaseCost(shoppingCar.getBaseCost() + list.get(i).getChosenNum()*shoppingCar.getMealsBoxFee());
//					shoppingCar.setTotalCost(shoppingCar.getTotalCost() + list.get(i).getChosenNum() * shoppingCar.getMealsBoxFee());
//				}
				shoppingCar.setBaseCost(shoppingCar.getBaseCost() + shoppingCar.getTotal() * shoppingCar.getMealsBoxFee());
				shoppingCar.setTotalCost(shoppingCar.getBaseCost());
			} else if(shoppingCar.getMealsBoxFeeType() == 1){
				shoppingCar.setBaseCost(shoppingCar.getBaseCost() + shoppingCar.getMealsBoxFee());
				shoppingCar.setTotalCost(shoppingCar.getTotalCost() + shoppingCar.getMealsBoxFee());
			}
			shoppingCar.setTotalCost(shoppingCar.getTotalCost() + shoppingCar.getdFee());
		}

		List<Gift> giftList = mActivitiesModel.getGiftList();
		if (giftList.size() > 0) {
			for (Gift g : giftList) {
				if(g.getPrice()>0){
					if (g.getQty() > 0 ) {
						shoppingCar.setTotalCost(shoppingCar.getTotalCost() + (g.getPrice() * g.getQty()));
					}
				}else if( g.getPrice()<0 ){
					shoppingCar.setTotalCost(shoppingCar.getTotalCost() + g.getPrice());
				}
				
			}
		}
		// 减去优惠卷的价格
		List<Coupon> coupons = getCouponList();
		for (int i = 0; i < coupons.size(); i++) {
			shoppingCar.setTotalCost(shoppingCar.getTotalCost() - Float.valueOf(coupons.get(i).getcValue()));
		}
		
		float totalCost = shoppingCar.getTotalCost();
		if( totalCost <= 0 ){
			shoppingCar.setTotalCost(0);
		}
		Log.i(TAG, "calculate 总金额"+shoppingCar.getTotalCost());
	}
	
	/**
	 * 获取餐盒费
	 * @return
	 */
	public float getMealsBoxFee(){
		float mealsBoxFee=0;
		List<IChoose> list = getChosenGoodsList();
		if (list.size() > 0) {
			// 添加餐盒费和外送费
			if (shoppingCar.getMealsBoxFeeType() == 2) {
				for (int i = 0; i < list.size(); i++) {
					mealsBoxFee=mealsBoxFee+list.get(i).getChosenNum() * shoppingCar.getMealsBoxFee();
				}
			} else if(shoppingCar.getMealsBoxFeeType() == 1){
				mealsBoxFee=shoppingCar.getMealsBoxFee();
			}
		}
		return mealsBoxFee;
	}
	
	/**
	 * 往购物车添加一个商品
	 * 
	 * @param goods
	 * @return boolean 是否新增
	 */
	public void addGoods(IChoose goods) {
		List<IChoose> goodsList = shoppingCar.getGoodsList();
		int indexOf = goodsList.indexOf(goods);
		if (indexOf == -1) {
			goodsList.add(goods);
		} else {
			goods =  goodsList.get(indexOf);
		}
		if(goods!=null){
			goods.setChosenNum(goods.getChosenNum() + 1);
		}
		calculate();
		if( goods instanceof Goods ){
			mGoodsController.recordGoods((Goods) goods);
		}else if( goods instanceof ChosenGoods ){
			mGoodsController.recordChosenGoods((ChosenGoods) goods);
		}
	}

	
	/**
	 * 从购物车中减去数量，当已选数量小于0的时候把该对象从购物车列表中移除
	 * 
	 * @param cg
	 * return boolean 是否移除了带属性的商品
	 */
	public void minusGoods(IChoose goods) {
		goods.setChosenNum(goods.getChosenNum()-1);
		if( goods.getChosenNum() <= 0 ){
			List<IChoose> goodsList = shoppingCar.getGoodsList();
			goodsList.remove(goods);
			if( goods instanceof Goods ){
				mGoodsController.delGoods((Goods) goods);
			}else if( goods instanceof ChosenGoods ){
				mGoodsController.delChosenGoods((ChosenGoods) goods);
			}
		}
		calculate();
	}
	
	
    /**
     * 调整原有的列表中的OptionGoods
     * @param adjustChosen
     * @param newOptionGoods
     */
	public void adjustOptionGoods(ChosenGoods adjustChosen,ChosenGoods newOptionGoods) {
		IChoose iChoose = getChosenGoodsById(newOptionGoods.getIds());
		//是否已经 存在相同属性的商品 
		if( iChoose != null ){
			//如果存在则合并数量并移除被调整前的商品
			iChoose.setChosenNum(iChoose.getChosenNum()+adjustChosen.getChosenNum());
			shoppingCar.getGoodsList().remove(adjustChosen);
			mGoodsController.delChosenGoods(adjustChosen);
		}else{
			adjustChosen.setIds(newOptionGoods.getIds());
			adjustChosen.setNames(newOptionGoods.getNames());
			adjustChosen.setPrice(newOptionGoods.getPrice());
			adjustChosen.setChosenOptList(newOptionGoods.getChosenOptList());
			adjustChosen.setChosenSGList(newOptionGoods.getChosenSGList());
		}

		calculate();
	}
	
	
	/**
	 * 根据Id获取购物车中的goods
	 * 
	 * @param ids
	 * @return
	 */
	public IChoose getChosenGoodsById(String ids) {
		for (IChoose cg : shoppingCar.getGoodsList()) {
			if (TextUtils.equals(ids, cg.getIds())) {
				return cg;
			}
		}
		return null;
	}


	/**
	 * 清除所有已选商品
	 */
	public void clearShopppingCar() {
		List<IChoose> goodsList = shoppingCar.getGoodsList();
		List<Coupon> couponList = shoppingCar.getCouponList();
		if (goodsList != null) {
			goodsList.clear();
		}
//		shoppingCar.setMealsBoxFee(0);
//		shoppingCar.setMealsBoxFeeType(-1);
		// shoppingCar.setToSendPrice(0);
		// shoppingCar.setdFee(0);
		shoppingCar.setBaseCost(0);
		setTotal(0);
		setTotalCost(0);
		couponList.clear();
		mActivitiesModel.clearActiviesCenter();
		mGoodsController.release();
		EventBus.getDefault().post(new EventShoppingCarChange());
	}

	
	/**
	 * 获取选中的所有商品对应的ChosenGoods列表
	 * 
	 * @return
	 */
	public List<IChoose> getChosenGoodsList() {
		List<IChoose> goodsList = shoppingCar.getGoodsList();
		return goodsList;
	}
	

	/**
	 * 获取要提交的 OrderGoodsItem 列表
	 * 
	 * @return
	 */
	public List<OrderGoodsItem> getOrderGoodsItemList() {
		List<OrderGoodsItem> items = new ArrayList<OrderGoodsItem>();
		List<IChoose> chosenGoodsList = getChosenGoodsList();
		for (IChoose cg : chosenGoodsList) {
			OrderGoodsItem item = new OrderGoodsItem();
			item.setgId(cg.getgId());
			item.setQty(cg.getChosenNum());
			item.setPrice(cg.getPrice());
			items.add(item);
			if( cg instanceof ChosenGoods ){
				item.setPrice(((ChosenGoods) cg).getParent().getPrice());
				item.setSubGList(getOrderSubGoodsList(cg));
				item.setOptList(getOrderOptionList(cg));
			}
		
		}
		return items;
	}

	
	/**
	 * 转换成要提交的对象
	 * 
	 * @return
	 */
	private List<OrderOptionItem> getOrderOptionList(IChoose cg) {
		List<Option> chosenOptList = cg.getChosenOptList();
		List<OrderOptionItem> orderOptionList = new ArrayList<OrderOptionItem>();
		for (Option opt : chosenOptList) {
			OrderOptionItem item = new OrderOptionItem(opt.getOptId());
			item.setPrice(opt.getPrice());
			orderOptionList.add(item);
		}
		return orderOptionList;
	}

	
	/**
	 * 转换成要提交的对象
	 * 
	 * @return
	 */
	private List<OrderSubGoodsItem> getOrderSubGoodsList(IChoose cg) {
		List<SubGoods> chosenSGList = cg.getChosenSGList();
		List<OrderSubGoodsItem> orderSubGoodsList = new ArrayList<OrderSubGoodsItem>();
		orderSubGoodsList.clear();
		for (SubGoods sg : chosenSGList) {
			OrderSubGoodsItem item = new OrderSubGoodsItem(sg);
			item.setPrice(sg.getPrice());
			orderSubGoodsList.add(item);
		}
		return orderSubGoodsList;
	}

	public void setShopDetail(ShopDetail shopDetail) {
		shoppingCar.setdFee(shopDetail.getSendFee());
		shoppingCar.setToSendPrice(shopDetail.getToSendPrice());
		shoppingCar.setMealsBoxFee(shopDetail.getMealsBoxFee());
		shoppingCar.setMealsBoxFeeType(shopDetail.getMealsBoxFeeType());
	}
	

	/**
	 * 获取购物车中的优惠卷列表(发送订单接口用到的实体列表)
	 * 
	 * @return
	 */
	public List<OrderCouponItem> getReqCouponsList() {
		List<OrderCouponItem> list = new ArrayList<OrderCouponItem>();
		for (Coupon c : shoppingCar.getCouponList()) {
			OrderCouponItem item = new OrderCouponItem();
			item.setcId(c.getcId());
			list.add(item);
		}
		return list;
	}

	
	/**
	 * 将选择的优惠券放入购物车
	 * 
	 * @param couponList
	 */
	public void setShoppingCarCounponList(List<Coupon> couponList) {
		setCouponList(couponList);
	}


	/**
	 * 获取基础总价
	 * 
	 * @return
	 */
	public float getBaseCost() {
		return shoppingCar.getBaseCost();
	}

	
	/**
	 * 重置名称,
	 * 是否需要加上单价
	 */
	public void restName(IChoose chosenGoods) {
		StringBuilder sb = new StringBuilder();
		float price = chosenGoods.getPrice();
		sb.append("<font color='#ff3278'><small>￥</small>"+ ParseUtils.formatPrice(price) + ":</font>");
		if(chosenGoods.getChosenOptList().size()>0||chosenGoods.getChosenSGList().size()>0){
			for (Option opt : chosenGoods.getChosenOptList()) {
				sb.append(opt.getOptName() + "+");
			}
			for (SubGoods sg : chosenGoods.getChosenSGList()) {
				int num = sg.getChosenNum();
				if (num <= 1) {
					sb.append(sg.getgName() + "+");
				} else {
					sb.append(sg.getgName() + "X" + num + "+");
				}
			}
		}else{
			sb.append("不加料+");
		}

		String tempName = sb.toString();
		if (!TextUtils.isEmpty(tempName) && tempName.length() > 1) {
			tempName = tempName.substring(0, tempName.length() - 1);
			chosenGoods.setNames(tempName);
		}

	}

	
}
